﻿using Qiniu.Http;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.Util;
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Ttifa.Infrastructure.Utils;
using Ttifa.WebBase.Result;

namespace Ttifa.Web.Controllers
{
    public class FileController : Controller
    {
        public ApiResult UpLoad(string id, string name, string type, string lastModifiedDate,
            int size, HttpPostedFileBase file)
        {
            string filePathName = string.Empty;
            string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload");
            if (Request.Files.Count == 0)
            {
                return new ApiResult(ApiStatus.Fail, "上传失败", name);
            }

            string ex = Path.GetExtension(file.FileName);
            filePathName = Guid.NewGuid().ToString("N") + ex;
            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }
            var fileName = Path.Combine(localPath, filePathName);
            file.SaveAs(fileName);

            return new ApiResult(ApiStatus.OK, "SUCCESS", fileName);
        }

        /// <summary>
        /// 配合lrz.bundle.js 上传base64字符串
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public ApiResult UpLoadByBase64(string filename)
        {
            if (Request["file"] == null)
                return new ApiResult(ApiStatus.Fail, $"{filename}上传失败");

            string filePathName = string.Empty;
            string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload");
            var fileStream = Request["file"].ToString();

            var reg = new Regex("data:image/.*;base64,", RegexOptions.IgnoreCase);
            var m = reg.Match(fileStream);
            if (m.Success && m.Index == 0)
                fileStream = fileStream.Substring(m.Length);

            string ex = Path.GetExtension(filename);
            filePathName = Guid.NewGuid().ToString("N") + ex;
            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }
            filePathName = Path.Combine(localPath, filePathName);
            StringToFile(fileStream, filePathName);

            return new ApiResult(ApiStatus.OK, "SUCCESS", filePathName);
        }

        public ApiResult Image()
        {
            var uploadInfo = new UploadInfo();
            string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload");
            if (Request.Files.Count == 0)
            {
                return new ApiResult(ApiStatus.Fail, "上传失败");
            }

            var file = Request.Files[0];
            uploadInfo.originalName = file.FileName;
            uploadInfo.name = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
            uploadInfo.url = "/Upload/" + uploadInfo.name;
            uploadInfo.size = file.ContentLength;
            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }
            file.SaveAs(Path.Combine(localPath, uploadInfo.name));

            return new ApiResult(ApiStatus.OK, "SUCCESS", uploadInfo);
        }

        /// <summary>
        /// base64字符串转为文件
        /// </summary>
        /// <param name="base64String"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool StringToFile(string base64String, string fileName)
        {
            var fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
            var bw = new System.IO.BinaryWriter(fs);
            if (!string.IsNullOrEmpty(base64String) && System.IO.File.Exists(fileName))
            {
                byte[] bytes = Convert.FromBase64String(base64String.Replace(" ", "+").Replace("%2B", "+"));
                bw.Write(bytes);
            }
            bw.Close();
            return true;
        }

        #region 七牛上传

        public ApiResult Upload2Qiniu(HttpPostedFileBase file)
        {
            var fs = file.InputStream;
            var filename = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
            var qiniuDomain = ConfigManager.GetSetting("qiniu.domain");

            var upResult = UploadData(fs, filename);
            //var upResult = UploadStream(fs, filename);
            if (upResult.Code != 200)
                return new ApiResult(ApiStatus.Fail, upResult.Text);

            return new ApiResult(data: $"{qiniuDomain}/{filename}");
        }

        public string GetToken(string filekey = "")
        {
            var ak = ConfigManager.GetSetting("qiniu.ak");
            var sk = ConfigManager.GetSetting("qiniu.sk");
            var bucket = ConfigManager.GetSetting("qiniu.bucket");
            Mac mac = new Mac(ak, sk);

            PutPolicy putPolicy = new PutPolicy();
            // "覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + filekey;
            putPolicy.Scope = bucket;
            putPolicy.SetExpires(3600);
            //自动删除
            //putPolicy.DeleteAfterDays = 1;
            return Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
        }

        private HttpResult UploadData(Stream fileStream, string fileName)
        {
            var token = GetToken();
            FormUploader fu = new FormUploader();
            byte[] byteData = new byte[fileStream.Length];
            fileStream.Read(byteData, 0, byteData.Length);

            return fu.UploadData(byteData, fileName, token);
        }

        private HttpResult UploadStream(Stream fileSteam, string fileName)
        {
            var token = GetToken();
            FormUploader fu = new FormUploader();

            return fu.UploadStream(fileSteam, fileName, token);
        }

        #endregion
    }
}
